package com.itheima.appserver.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.itheima.appserver.config.NoAuthorization;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.pojo.User;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class Tokeninterceptor implements HandlerInterceptor {


    /*
     * 请求到达目标资源之前
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 请求的资源必须是Controller中的方法
        // 如果不是Controller中的方法就直接放行

        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        // Token的解析
        if (((HandlerMethod) handler).hasMethodAnnotation(NoAuthorization.class)) {
            return true;
        }

//获取token
        String token = request.getHeader("Authorization");
        //如果token是空
        boolean blank = StrUtil.isBlank(token);
        if (blank) {
            response.setStatus(401);
            return false;
        }
        //校验token是否有效
        // 开始校验Token是否有效
        JWT jwt = JWTUtil.parseToken(token);
        jwt.setKey(Constants.JWT_SECRET.getBytes());
        if (!jwt.verify() || !jwt.validate(0)) {
            response.setStatus(401);
            return false;
        }

        Object uid = jwt.getPayload("uid");
        Object phoneNum = jwt.getPayload("phoneNum");

        User user = User.builder().id(Convert.toLong(uid)).mobile(Convert.toStr(phoneNum)).build();
        UserThreadLocal.set(user);
        return true;

    }

    /*
     * 中间*/
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);

    }

    /*
     * 请求到达目标资源之后
     * */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除线程上得数据
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
